window.onload = function() {
    const $ = name => document.querySelector(name);
    var token1 = window.localStorage.getItem('token');
    var logging = $('.logging');
    var mask = $('.wrapper');
    var loginbtn1 = document.getElementById('loginbtn1');
    var loginbtn2 = document.getElementById('loginbtn2');
    var loginbtn3 = document.getElementById('loginbtn3');
    var rlogo = document.getElementById('rlogo');
    var userinfo = document.getElementById('userinfo');
    var dropbtn = $('.dropdown');
    var teacherlogo = document.getElementById('teachercentre');
    axios.defaults.timeout = 5500;
    axios.defaults.baseURL = 'http://120.24.80.83:3000';
    // axios.defaults.headers.common['Authorization'] = token1;
    axios.interceptors.request.use(function(config) {
        // 在发送请求之前做些什么
        // 若token存在， 则在每次请求头中加入token
        if (window.localStorage.getItem('token')) {
            config.headers.Authorization = window.localStorage.getItem('token');
            // axios.defaults.headers.common['Authorization'] = window.localStorage.getItem('token');
        }
        // console.log(config);
        return config;
    }, function(error) {
        // 对请求错误做些什么
        return Promise.reject(error);
    });
    axios.interceptors.response.use(
            response => {
                if (getCookie("init")) {
                    var cookie = JSON.parse(getCookie("init"));
                } else {
                    var cookie = new Object();
                    var cookie = {
                        name: '',
                        pass: ''
                    };
                }
                if (response.data.msg == '登录失效' && (cookie.name == '' && cookie.pass == '')) {
                    // 这里写清除token的代码
                    // 清除token
                    console.log(response.data.msg);
                    setTimeout(() => {
                        // window.open('login.html');
                        loginbtn1.style.display = 'block';
                        loginbtn2.style.display = 'block';
                        loginbtn3.style.display = 'block';
                        rlogo.style.display = 'none';
                        userinfo.style.display = 'none';
                        userinfo.style.height = '0';
                    }, 3000);
                    // window.localStorage.removeItem('token');
                    console.log('登录过期，请重新登录');
                    Message({
                        message: '登录过期，请重新登录',
                        duration: 1000,
                        forbidClick: true
                    });
                    Message();
                    // window.location.href = 'login.html';
                } //else if ((response.data.code == 1 && (cookie.name != '' && cookie.pass != '')) || (response.data.code == 1 && (cookie.name == '' && cookie.pass == ''))) {
                //     console.log('登录状态');
                //     loginbtn1.style.display = 'none';
                //     loginbtn2.style.display = 'none';
                //     loginbtn3.style.display = 'none';
                //     rlogo.style.display = 'block'
                //     userinfo.style.display = 'block';
                //     if (window.localStorage.getItem('avatar')) {
                //         document.querySelector('#rlogo img').src = window.localStorage.getItem('avatar');
                //     }
                // }
                return response;
            },
            error => {
                if (error.response) {
                    switch (error.response.status) {
                        case 403:
                            // 这里写清除token的代码
                            console.log('清除token');
                            id1 = '';
                            Message({
                                message: '登录过期，请重新登录',
                                duration: 1000,
                                forbidClick: true
                            });
                            // 清除token
                            window.loaclStorage.removeItem('token');
                            // store.commit('loginSuccess', null);
                            // 跳转登录页面，并将要浏览的页面fullPath传过去，登录成功后跳转需要访问的页面
                            // setTimeout(() => {
                            //     router.replace({
                            //         path: '/login',
                            //         query: {
                            //             redirect: router.currentRoute.fullPath
                            //         }
                            //     });
                            // }, 1000);
                            break;
                    }
                }
                return Promise.reject(error.response.data)
            }
        )
        //页面加载时，如果有记录7天免登录
    if (getCookie("init")) {
        var cookie = JSON.parse(getCookie("init"));
        if (cookie.name != '' && cookie.pass != '') {
            axios({
                    url: "/login",
                    method: "post",
                    data: {
                        "username": cookie.name,
                        "password": cookie.pass,
                    }
                })
                .then(function(response) {
                    console.log(response.data);
                    var res = response.data.data;
                    //使用loackstorge保存token，方便以后需要的时候用
                    personBusi();
                    window.localStorage.setItem("token", res.token);
                    loginbtn1.style.display = 'none';
                    loginbtn2.style.display = 'none';
                    loginbtn3.style.display = 'none';
                    rlogo.style.display = 'block';
                    userinfo.style.display = 'block';
                    dropbtn.style.display = 'inline-block';
                    if (window.localStorage.getItem('avatar')) {
                        document.querySelector('#rlogo img').src = window.localStorage.getItem('avatar');
                    }
                    document.getElementById('userinfo').innerHTML = '用户' + '&nbsp' + res.username;
                    if (res.avatar) {
                        document.querySelector('#rlogo img').src = res.avatar;
                    } else {
                        document.querySelector('#rlogo img').src = "img/register.png";
                    }
                    if (res.role == 'teacher') {
                        teacherlogo.style.display = 'block';
                        document.getElementById('rolelogo').innerHTML = '教师';
                    } else if (res.role == 'student') {
                        teacherlogo.style.display = 'none';
                        document.getElementById('rolelogo').innerHTML = '学生';
                    }
                })
        } else {
            console.log('cookie已注销');
            dropbtn.style.display = 'none';
        }
    }
    //封装每隔五分钟发送请求的函数
    function personBusi() {
        var cookie = JSON.parse(getCookie("init"));
        setTimeout(personBusi, 1000 * 60 * 5); //这里的1000表示1秒有1000毫秒,1分钟有60秒,5表示总共5分钟 
        axios({
                url: "/login",
                method: "post",
                data: {
                    "username": cookie.name,
                    "password": cookie.pass,
                }
            })
            .then(response => {
                if (response.data.code == 1) {
                    var res1 = response.data.data;
                    console.log('刷新token');
                    rlogo.style.display = 'block';
                    userinfo.style.display = 'block';
                    dropbtn.style.display = 'inline-block';
                    window.localStorage.removeItem("token");
                    window.localStorage.setItem("token", res1.token);
                    document.getElementById('userinfo').innerHTML = '用户' + '&nbsp' + res1.username;
                    if (res1.role == 'teacher') {
                        teacherlogo.style.display = 'block';
                        document.getElementById('rolelogo').innerHTML = '教师';
                    } else if (res1.role == 'student') {
                        teacherlogo.style.display = 'none';
                        document.getElementById('rolelogo').innerHTML = '学生';
                    }
                    if (res1.avatar) {
                        document.querySelector(".pic img").src = res1.avatar;
                    } else {
                        document.querySelector('#rlogo img').src = "img/register.png";
                    }
                }
            })

    }
    //验证token是否失效
    if (window.localStorage.getItem("token")) {
        axios({
            method: 'post',
            url: '/refresh',
        }).then(response => {
            var res = response.data;
            console.log(res);
            if (res.code == 1) {
                var id3 = window.localStorage.getItem('username');
                loginbtn1.style.display = 'none';
                loginbtn2.style.display = 'none';
                loginbtn3.style.display = 'none';
                userinfo.style.display = 'block';
                rlogo.style.display = 'block';
                dropbtn.style.display = 'inline-block';
                if (window.localStorage.getItem('avatar')) {
                    document.querySelector('#rlogo img').src = window.localStorage.getItem('avatar');
                } else {
                    document.querySelector('#rlogo img').src = "img/register.png";
                }
                document.getElementById('userinfo').innerHTML = '用户' + '&nbsp' + id3;
                var role3 = window.localStorage.getItem('role');
                if (role3 == 'teacher') {
                    teacherlogo.style.display = 'block';
                    document.getElementById('rolelogo').innerHTML = '教师';
                } else if (role3 == 'student') {
                    teacherlogo.style.display = 'none';
                    document.getElementById('rolelogo').innerHTML = '学生';
                }
                console.log('token有效');
            } else {
                console.log('error');
            }

        }).catch(err => {

        })
    }
    //登录

    var login = document.getElementById('submit');
    var username = document.getElementById('username');
    var password = document.getElementById('password');
    var role = '';
    var role1 = '';
    var token1 = '';
    var id1 = '';
    var avatar = '';

    login.addEventListener('click', function() {

            var un1 = username;
            var pw1 = password;
            axios({
                method: 'post',
                url: '/login',
                data: {
                    username: un1.value,
                    password: pw1.value,
                } //params是拼接参数请求，而data是把参数放进请求体
            }).then(response => {
                var res = response.data;
                console.log(res);
                if (res.code == 1) {
                    console.log('登录成功');
                    document.getElementById('userinfo').innerHTML = '用户' + '&nbsp' + res.data.username;
                    document.getElementById('loginbtn3').disabled = false;
                    loginbtn1.style.display = 'none';
                    loginbtn2.style.display = 'none';
                    loginbtn3.style.display = 'none';
                    rlogo.style.display = 'block';
                    userinfo.style.display = 'block';
                    logging.style.display = 'none';
                    mask.style.display = 'none';
                    dropbtn.style.display = 'inline-block';
                    window.localStorage.removeItem('username');
                    window.localStorage.removeItem('token');
                    window.localStorage.removeItem('role');
                    window.localStorage.removeItem('id');
                    window.localStorage.removeItem('avatar');
                    window.localStorage.removeItem('password');
                    console.log('欢迎' + res.data.username);
                    token1 = res.data.token;
                    id1 = res.data.id;
                    role = res.data.role;
                    if (res.data.role == 'teacher') {
                        teacherlogo.style.display = 'block';
                        document.getElementById('rolelogo').innerHTML = '教师';
                    } else if (res.data.role == 'student') {
                        teacherlogo.style.display = 'none';
                        document.getElementById('rolelogo').innerHTML = '学生';
                    }
                    if (res.data.avatar) {
                        avatar = res.data.avatar;
                        window.localStorage.setItem('avatar', avatar);
                        document.querySelector('#rlogo img').src = window.localStorage.getItem('avatar');
                    } else {
                        document.querySelector('#rlogo img').src = "img/register.png";
                    }
                    // console.log(token1);
                    if (token1) {
                        // window.localStorage.removeItem('token');
                        window.localStorage.setItem('token', token1);
                        window.localStorage.setItem('role', role);
                        window.localStorage.setItem('id', id1);
                        window.localStorage.setItem('username', un1.value);
                        window.localStorage.setItem('password', pw1.value);
                    }
                } else if (res.msg = '用户名或密码错误') {
                    document.getElementById('error').innerHTML = '用户名或密码错误';
                    setTimeout(() => {
                        document.getElementById('error').innerHTML = '';
                    }, 2000);
                    console.log('error');
                }

            })
        })
        //注册
    var register1 = document.querySelector('#register1');
    var username1 = document.querySelector('#username1');
    var password1 = document.querySelector('#password1');
    var teacher = document.querySelector('#teacher');
    var student = document.querySelector('#student');

    teacher.addEventListener('change', function() {
        if (this.checked) {
            role1 = 'teacher';
        }
    })
    student.addEventListener('change', function() {
        if (this.checked) {
            role1 = 'student';
        }
    })

    register1.addEventListener('click', function() {

            var un2 = username1;
            var pw2 = password1;
            axios({
                method: 'post',
                url: '/register',
                data: {
                    username: un2.value,
                    password: pw2.value,
                    role: role1
                } //params是拼接参数请求，而data是把参数放进请求体
            }).then(response => {
                var res = response.data;
                console.log(res);
                if (res.code == 1) {
                    console.log('注册成功');
                    document.getElementById('error1').innerHTML = '注册成功';
                } else if (res.msg = '该用户已经被注册过了') {
                    document.getElementById('error1').innerHTML = '该用户名已被使用';
                    setTimeout(() => {
                        document.getElementById('error1').innerHTML = '';
                        var u = document.getElementById('username1');
                        u.value = '';
                        var p = document.getElementById('password1');
                        p.value = '';
                    }, 2000)

                    console.log('error');
                }

            })
        })
        //七天免登录
        //设置cookie
    function setCookie(_name, val, expires) {
        var d = new Date();
        d.setDate(d.getDate() + expires);
        document.cookie = _name + "=" + val + ";path=/;expires=" + d.toGMTString();
    }

    //获取cookie
    function getCookie(_name) {
        var cookie = document.cookie;
        var arr = cookie.split("; ");
        for (var i = 0; i < arr.length; i++) {
            var newArr = arr[i].split("=");
            if (newArr[0] == _name) {
                return newArr[1];
            }
        }
    }
    /*
       如何将json对象转换为字符串
           JSON.stringify(对象);
           返回值是一个字符串
       如何将字符串转换为json对象
           JSON.parse(字符串)
           返回值是对象
    */
    //删除cookie
    var oBtn = document.getElementById("submit");
    var oUser = document.getElementById("username");
    var oPass = document.getElementById("password");
    var oCheck = document.getElementById("check1");

    if (getCookie("init")) {
        var cookie = JSON.parse(getCookie("init"));
        oUser.value = cookie.name;
        oPass.value = cookie.pass;
        oCheck.checked = true;
    }

    oBtn.onclick = function() {
        if (oCheck.checked) {
            var obj = {};
            obj.name = oUser.value;
            obj.pass = oPass.value;
            var str = JSON.stringify(obj);
            setCookie("init", str, 7);
        }
    }

    //退出登录的函数
    function Outlogin() {
        loginbtn1.style.display = 'block';
        loginbtn2.style.display = 'block';
        loginbtn3.style.display = 'block';
        rlogo.style.display = 'none';
        userinfo.style.display = 'none';
        teacherlogo.style.display = 'none';
        dropbtn.style.display = 'none';
        window.localStorage.removeItem("token");
        var obj = {};
        obj.name = '';
        obj.pass = '';
        var str = JSON.stringify(obj);
        setCookie("init", str, 0.000001);
    }

    //退出登录
    document.querySelector("#out-login").addEventListener('click', function() {
            Outlogin();
        })
        //滚动条事件小火箭平滑运行
    var obtn = document.getElementById('return_top'); //获取回到顶部按钮的ID
    var clientHeight = document.documentElement.clientHeight; //获取可视区域的高度
    var timer = null; //定义一个定时器
    var isTop = true; //定义一个布尔值，用于判断是否到达顶部

    window.onscroll = function() { //滚动条滚动事件

        //获取滚动条的滚动高度
        var osTop = document.documentElement.scrollTop || document.body.scrollTop;

        if (osTop >= clientHeight) { //如果滚动高度大于可视区域高度，则显示回到顶部按钮
            obtn.style.display = 'block';
        } else { //否则隐藏
            obtn.style.display = 'none';
        }

        //主要用于判断当 点击回到顶部按钮后 滚动条在回滚过程中，若手动滚动滚动条，则清除定时器
        if (!isTop) {
            clearInterval(timer);
        }
        isTop = false;
    }

    obtn.onclick = function() { //回到顶部按钮点击事件
            //设置一个定时器
            timer = setInterval(function() {
                //获取滚动条的滚动高度
                var osTop = document.documentElement.scrollTop || document.body.scrollTop;
                //用于设置速度差，产生缓动的效果
                var speed = Math.floor(-osTop / 6);
                document.documentElement.scrollTop = document.body.scrollTop = osTop + speed;
                isTop = true; //用于阻止滚动事件清除定时器
                if (osTop == 0) {
                    clearInterval(timer);
                }
            }, 30);
        }
        //主页展开部分
    var spread = document.querySelector('.arrow-spread');
    var shrink = document.querySelector('.arrow-shrink');
    var courselist1 = document.querySelector('.eight-course-list1');
    var courselist2 = document.querySelector('.eight-course-list2');
    var courselist3 = document.querySelector('.eight-course-list3');

    spread.addEventListener('click', function() {
        spread.style.display = 'none';
        courselist1.style.height = "300px";
        courselist2.style.height = "300px";
        courselist3.style.height = "300px";
        shrink.style.display = 'block';
    })
    shrink.addEventListener('click', function() {
        spread.style.display = 'block';
        courselist1.style.height = "0.001px";
        courselist2.style.height = "0.001px";
        courselist3.style.height = "0.001px";
        shrink.style.display = 'none';
    })

    //主页课程分类渲染
    var opt1 = document.querySelectorAll('.opt');
    Getcourse(0);
    var demo1 = $(".detail-page");

    function Getcourse(a) {
        axios({
            method: 'get',
            url: '/course/courseList',
            params: {
                classifyId: a
            } //params是拼接参数请求，而data是把参数放进请求体
        }).then(res => {
            let str = res.data.data;
            console.log(str.length);
            if (a != 0) {
                demo1.innerHTML = '';
            }
            for (let t = 0; t < str.length; t++) {
                let div = document.createElement("div");
                div.className = "detail-box";
                if (str[t].originalPrice != null & str[t].originalPrice != '') {
                    div.setAttribute('courseid', str[t].id);
                    div.innerHTML = ` 
                <div class="detail-pic">
                    <img src="${str[t].image}"  data-src="${str[t].image}" alt="loading" class="la">
                </div>
                <div class="detail-message ">
                    <p class="message-1 ">
                       ${str[t].title}
                    </p>
                    <p class="message-2 ">
                        ${str[t].brief}
                    </p>
                    <p class="message-3 ">
                        ${str[t].teacherTitle}
                    </p>
                    <div class="service ">
                        <div class="total-price ">
                            <span class="price-money ">￥</span>
                            <span class="price-num ">${str[t].price}</span>
                            <span class="_oldprice">¥${str[t].originalPrice}</span></div>
                            <span class="eight-num-show ">${str[t].pruchasedCount}</span>
                        </div>
                    </div>
                </div>`;
                } else {
                    div.setAttribute('courseid', str[t].id);
                    div.innerHTML = ` 
                    <div class="detail-pic">
                        <img src="${str[t].image}" data-src="${str[t].image}" alt="loading" class="la">
                    </div>
                    <div class="detail-message ">
                        <p class="message-1 ">
                           ${str[t].title}
                        </p>
                        <p class="message-2 ">
                            ${str[t].brief}
                        </p>
                        <p class="message-3 ">
                            ${str[t].teacherTitle}
                        </p>
                        <div class="service ">
                            <div class="total-price ">
                                <span class="price-money ">￥</span>
                                <span class="price-num ">${str[t].price}</span>
                                <span class="eight-num-show ">${str[t].pruchasedCount}</span>
                            </div>
                        </div>
                    </div>`;
                }
                demo1.appendChild(div);
            }
            demo1.innerHTML += `<div class="detail-box " id="last-detail-box " style="opacity:0;"></div>`;
            // lazyload();
            // window.onscroll = throttle(lazyload, 200);
            to_detailpage();
        }).catch(() => {
            console.log('获取课程失败');
        })
    }
    console.log(opt1.length);
    Appendcourse();

    function Appendcourse() {
        for (let i = 0; i < opt1.length; i++) {
            opt1[i].onclick = function() {
                if (i == 0) {
                    demo1.innerHTML = '';
                }
                Getcourse(i);
            }
        }
    }

    function to_detailpage() {
        var coursebox = document.querySelectorAll('.detail-box');
        for (let i = 0; i < coursebox.length; i++) {
            let courseid = coursebox[i].getAttribute('courseid');
            coursebox[i].onclick = function() {
                window.localStorage.setItem('courseid', courseid);
                console.log('1');
                setTimeout(() => {
                    Ifbuy();
                }, 500)
            }
        }
    }

    function Ifbuy() {
        axios({
            method: 'post',
            url: '/course/hasBuyCourse',
            data: {
                userId: window.localStorage.getItem('id'),
                courseId: window.localStorage.getItem('courseid')
            }
        }).then(res => {
            console.log(res.data);
            if (res.data.msg == '已经购买了该课程') {
                window.location.href = '../course-details/course-details-three.html';
            } else {
                window.location.assign('../course-details/course-details-two.html');
                console.log('1');
            }
        })
    }
    //实现图片懒加载


    //实现图片懒加载以及节流函数
    // let n = 0;
    // var lazyload = function() {
    //     let imgs = document.querySelectorAll('.la');
    //     let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
    //     let winTop = window.innerHeight;
    //     for (let i = n; i < imgs.length; i++) {
    //         if (imgs[i].offsetTop < scrollTop + winTop) {
    //             if (imgs[i].getAttribute('data-src')) {
    //                 imgs[i].src = imgs[i].getAttribute('data-src');
    //                 console.log(i + 1);
    //             }
    //         }
    //         n++; //不从第一张遍历
    //     }
    // }

    // function throttle(method, delay) {
    //     var timer = null;
    //     return function() {
    //         var context = this,
    //             args = arguments;
    //         clearTimeout(timer);
    //         timer = setTimeout(function() {
    //             method.apply(context, args);
    //         }, delay);
    //     }
    // }
    // window.onscroll = throttle(lazyload, 200);
    //搜索功能模块
    var search_input = $('.search-input');
    var search_content = $('.search-content');
    var search_box = $('.search');
    search_input.addEventListener('input', function() {
        var value = this.value.replace(/\s/g, '')
        if (value != '') {
            search(value);
        } else {
            clearTimeout(timer);
            $('.search-content').style.display = 'none';
            search_content.innerHTML = '';
        }
    })
    search_input.addEventListener('focus', function() {
        this.style.color = '#333'
    })
    search_input.addEventListener('blur', function() {
        this.style.color = '#999'
        setTimeout(() => {
            search_input.value = '';
        }, 1000);
    })
    search_box.addEventListener('click', function(e) {
        e.stopPropagation()
        var value = search_input.value.replace(/\s/g, '')
        if (value != '') {
            search_content.style.height = '320px';
            $('.search-content').style.display = 'block';
        }
    })
    document.addEventListener('click', function() {
        search_content.style.display = 'none';
    })
    var to_search = $('.to_search');
    to_search.addEventListener('click', function() {
        var value = search_input.value.replace(/\s/g, '');
        if (value != '') {
            window.localStorage.title = value;
            window.location.href = '../Searchcourse/searchcourse.html';
        }
    })
    window.addEventListener('keyup', function(e) {
            if (e.keyCode == 13 && search_input.value != '' && search_input == document.activeElement) {
                to_search.click()
            }
        })
        //利用防抖函数优化搜索课程功能
    var timer = null

    function search(value) {
        clearTimeout(timer)
        timer = setTimeout(function() {
            axios({
                url: '/course/search',
                params: {
                    title: value
                }
            }).then(response => {
                if (response.data.msg == '查找成功') {
                    var data = response.data.data
                    var str = ''
                    for (var k in data) {
                        str +=
                            `<li courseid="` + data[k].id + `">
                       <img src="` + data[k].image + `" alt="">
                       <div class="course-info">
                           <h2 class="course-title">` + data[k].title + `</h2>
                           <div class="teacher-info">
                               <span class="teacher-name">` + data[k].teacherName + `</span>
                               <span class="teacher-work">` + data[k].teacherTitle + `</span>
                           </div>
                       </div>
                   </li>`
                    }
                    search_content.innerHTML = str;
                    var course_titles = search_content.querySelectorAll('.course-title');
                    var course_titles_len = course_titles.length;
                    var teacher_names = document.querySelectorAll('.teacher-name');
                    var teacher_works = document.querySelectorAll('.teacher-work');
                    var reg = new RegExp(value, "g");
                    for (var i = 0; i < course_titles_len; i++) {
                        course_titles[i].innerHTML = course_titles[i].innerHTML.replace(reg, '<span class="highlight">' + value + '</span>')
                        teacher_names[i].innerHTML = teacher_names[i].innerHTML.replace(reg, '<span class="highlight">' + value + '</span>')
                        teacher_works[i].innerHTML = teacher_works[i].innerHTML.replace(reg, '<span class="highlight">' + value + '</span>')
                    }
                    $('.search-content').style.display = 'block';
                }
                console.log(response.data);
                var li1 = document.querySelectorAll('li');
                for (let t = 0; t < li1.length; t++) {
                    li1[t].addEventListener('click', function() {
                        window.localStorage.setItem('courseid', li1[t].getAttribute('courseid'));
                        setTimeout(() => {
                            Ifbuy();
                        }, 500)
                    })
                }
            }).catch(err => {
                console.log(err);
            })
            console.log(value)
        }, 800)
    }


    //专栏点击显示下划线
    var opts = document.querySelectorAll('.opt');

    for (var i = 0; i < opts.length; i++) {
        opts[i].addEventListener('click', function() {

            for (var j = 0; j < opts.length; j++) {
                opts[j].className = 'opt';
            }
            this.className = 'opt opt-change';
        })
    }








}